package wineshop.domain.market;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import wineshop.domain.general.Address;
import wineshop.domain.general.Country;

public class CostumerTest {
	Seller laVersa;
	Product product;
	Address address;
	Item wine;

	@Before
	public void setUp() {
		Country italy = new Country("Italy");
		Country spain = new Country("Spain");
		Address addressLaVersa = new Address("Via F.Crispi", "15",
				"Santa Maria della Versa", "27047", italy);
		Address addressTorres = new Address("M. Torres", "6", "Barcelona",
				"08720", spain);
		laVersa = new Seller("La Versa", addressLaVersa);
		product = new Product("Spumante", "Italian dessert wine.", "white", 75,
				12.0);
		address = addressTorres;
		wine = laVersa.makeNewItem(product, "ABC", 1000, 2006);
		laVersa.changeAvailability(true, wine);
	}

	@Test
	public void shouldCustomerBuyAvailableItem() {
		assertTrue(wine.isAvailable());
		Customer customer = new Customer("tom", "jones", "tjones");
		Purchase purchase = customer.buy(wine, new Creditcard("123", customer),
				address);
		assertNotNull(purchase);
	}

	@Test
	public void shouldNotCustomerBuyAnavailableItem() {
		laVersa.changeAvailability(false, wine);
		assertFalse(wine.isAvailable());
		Customer customer = new Customer("tom", "jones", "tjones");
		Exception e;
		try {
			customer.buy(wine, new Creditcard("123", customer), address);
			e = null;
		} catch (RuntimeException rte) {
			e = rte;
		}
		assertNotNull(e);
	}

	@Test
	public void shouldNotCustomerBuySoldItem() {
		Customer customer = new Customer("tom", "jones", "tjones");
		laVersa.sell(wine, customer, new Creditcard("123", customer), address);
		assertTrue(wine.isSold());

		Customer customer2 = new Customer("bob", "smith", "bsm");
		Exception e;
		try {
			customer2.buy(wine, new Creditcard("567", customer2), address);
			e = null;
		} catch (RuntimeException rte) {
			e = rte;
		}
		assertNotNull(e);
	}

	@Test
	public void shouldNotCustomerBuyWithOthersCreditCard() {
		Customer customer = new Customer("tom", "jones", "tjones");
		Creditcard tomCard = new Creditcard("123", customer);
		laVersa.sell(wine, customer, tomCard, address);

		Customer customer2 = new Customer("bob", "smith", "bsm");
		Exception e;
		try {
			customer2.buy(wine, tomCard, address);
			e = null;
		} catch (RuntimeException rte) {
			e = rte;
		}
		assertNotNull(e);
	}

	@Test
	public void shouldNotCustomerBuyTheSameItemTwice() {
		Customer customer = new Customer("tom", "jones", "tjones");
		Creditcard card = new Creditcard("123", customer);
		Purchase purchase = customer.buy(wine, card, address);
		assertNotNull(purchase);

		Exception e;
		try {
			customer.buy(wine, card, address);
			e = null;
		} catch (RuntimeException rte) {
			e = rte;
		}
		assertNotNull(e);
	}

	@After
	public void tearDown() {
		laVersa = null;
		product = null;
		address = null;
		wine = null;
	}
}
